<template>
  <div class="rank_header">
    <div class="title">
      <span>商品热销榜</span>
    </div>
  </div>
  <van-pull-refresh v-model="refreshing" @refresh="OnRefresh">
    <van-list
      v-model:loading="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="OnLoad"
    >
      <div class="rank_box">
        <div class="item" v-for="(item, index) in list" :key="item.id">
          <div class="top">
            <div class="img">
              <img :src="item.products.thumb_text" />
            </div>
            <div class="content">
              <div class="title">{{ item.products.name }}</div>
              <p class="middle">
                <span>{{ item.products.flag_text }}</span>
              </p>
              <p class="desc" v-if="item.comment">热评：{{ item.comment }}</p>
            </div>
          </div>
          <div class="footer">
            <div class="price">
              ￥<span>{{ item.products.price }}</span>
              活动价
              <span>极速退款</span>
            </div>
            <div class="btn" @click="ToProductInfo(item.products.id)">
              去购买>
            </div>
          </div>
          <div class="tip">
            <img src="/assets/images/hot.png" />
            <span>Top.{{ index + 1 }}</span>
          </div>
        </div>
      </div>
    </van-list>
  </van-pull-refresh>
</template>

<script setup>
// this代理
const { proxy } = getCurrentInstance();
// 榜单数据
const list = ref([]);
// 刷新状态
const refreshing = ref(false);
// 懒加载状态
const loading = ref(false);
// 加载状态
const finished = ref(false);
// 当前页
const page = ref(1);

// 挂载前钩子
onBeforeMount(() => OnRefresh());

// 下拉刷新
const OnRefresh = () => {
  page.value = 1;
  list.value = [];
  finished.value = false;
  loading.value = true;
  refreshing.value = true;

  setTimeout(OnLoad, 1000);
};

// 上拉加载
const OnLoad = async () => {
  // 如果是下拉刷新，重置其值
  if (refreshing.value === true) {
    refreshing.value = false;
  }
  // 组装参数
  let params = {
    page: page.value,
  };
  // 发起请求
  let result = await proxy.$http.post({
    url: "/product/rank",
    params,
  });
  // 取消加载
  loading.value = false;
  // 处理请求结果
  if (result.code === 1) {
    // 获取数据总数
    let count = result.data ? result.data.count : 0;
    // 获取数据并且合并数组
    list.value = result.data ? list.value.concat(result.data.list) : [];
    // 判断是否加载完所有数据
    if (list.value.length >= count) {
      // 完成加载
      finished.value = true;
      return;
    }
    // 分页+1
    page.value = page.value + 1;
  } else {
    finished.value = true;
  }
};

// 跳转到商品详情页
const ToProductInfo = (proid) => {
  proxy.$router.push({
    path: "/product/info",
    query: { proid },
  });
};
</script>

<style scoped>
@import url("/assets/css/ProductRank.css");
</style>